package com.guli.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.guli.common.utils.R;
import com.guli.gulimall.product.entity.SkuImagesEntity;
import com.guli.gulimall.product.entity.SpuInfoDescEntity;
import com.guli.gulimall.product.entity.SpuInfoEntity;
import com.guli.gulimall.product.feign.SeckillFeignService;
import com.guli.gulimall.product.service.*;
import com.guli.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimall.product.dao.SkuInfoDao;
import com.guli.gulimall.product.entity.SkuInfoEntity;
import org.springframework.transaction.annotation.Transactional;


@Service("skuInfoService")
public class SkuInfoServiceImpl
        extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    private SkuImagesService imagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wapper = new QueryWrapper<>();
        /**

         * catelogId: 0,
         * : 0,
         * min: 0,
         * max: 0
         */
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wapper.and(w->{
                w.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        //分类id
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)){
            if(!"0".equalsIgnoreCase(catelogId)){
                wapper.eq("catalog_id",catelogId);
            }
        }

        //品牌ID
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)){
            if(!"0".equalsIgnoreCase(brandId)) {
                wapper.eq("brand_id", brandId);
            }
        }

        //价格区间
        String min = (String) params.get("min");
        if(!StringUtils.isEmpty(min)){
            wapper.ge("price",min);
        }

        String max = (String) params.get("max");
        if(!StringUtils.isEmpty(max)){
            try{
                BigDecimal bigDecimal = new BigDecimal(max);
                if( bigDecimal.compareTo(new BigDecimal("0"))==1){
                    wapper.le("price",max);
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        List<SkuInfoEntity> skus = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id",spuId));
        return skus;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1.sku基本信息获取 pms_sku_info
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, threadPoolExecutor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((skuInfo) -> {
            //3.获取spu的销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrBySpuId(skuInfo.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        }, threadPoolExecutor);

        CompletableFuture<Void> spuInfoDescFuture = infoFuture.thenAcceptAsync((skuInfo) -> {
            //4.获取spu的介绍 pms_spu_info_desc
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(skuInfo.getSpuId());
            skuItemVo.setDesp(spuInfoDesc);
        }, threadPoolExecutor);

        CompletableFuture<Void> spuItemAttrGroupFuture = infoFuture.thenAcceptAsync((skuInfo) -> {
            //5.获取spu的规格参数信息
            List<SpuItemAttrGroupVo> groupAttrs = attrGroupService.getAttrGroupWithAttrBySpuId(skuInfo.getSpuId(), skuInfo.getCatalogId());
            skuItemVo.setGroupAttrs(groupAttrs);
        }, threadPoolExecutor);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //2.sku的图片信息  pms_sku_images
            List<SkuImagesEntity> skuImages = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(skuImages);
        }, threadPoolExecutor);

        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            //6. 查询当前sku是否参与秒杀优惠
            R r = seckillFeignService.getSkuSeckillInfo(skuId);
            if (r.getCode() == 0) {
                SeckillInifoVo seckillInfo = r.getData(new TypeReference<SeckillInifoVo>() {
                });
                skuItemVo.setSeckillSkuVo(seckillInfo);
            }
        }, threadPoolExecutor);

        //等待所有任务都完成
        CompletableFuture<Void> allFuture = CompletableFuture.allOf(saleAttrFuture, spuInfoDescFuture, spuItemAttrGroupFuture, imageFuture,seckillFuture);
        allFuture.get();
        return skuItemVo;
    }

}